package redis.client.nedis.request;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import redis.client.nedis.HostAndPort;
import redis.client.nedis.commands.RedisCommand;
import redis.client.nedis.reply.IReply;

import java.util.concurrent.Semaphore;
import java.util.function.Consumer;

/**
 * redis请求
 *
 * @author gaodong
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class RedisRequest {
    /**
     * 命令唯一id，用于全局搜索
     */
    private long id;

    /**
     * redis命令
     */
    private RedisCommand command;

    /**
     * redis服务器地址
     */
    private HostAndPort hostAndPort;

    /**
     * 服务器返回值
     */
    private IReply<?> reply;

    /**
     * 信号量，用于返回结果时通知
     */
    private Semaphore semaphore = new Semaphore(1);

    private Consumer<RedisRequest> callback;

    public RedisRequest(RedisCommand cmd, HostAndPort hp) {
        this.command = cmd;
        this.hostAndPort = hp;
    }

    public RedisRequest(RedisCommand cmd, HostAndPort hp, Consumer<RedisRequest> cb) {
        this.command = cmd;
        this.hostAndPort = hp;
        this.callback = cb;
    }

    public void acquireMutex() {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void releaseMutex() {
        semaphore.release();
    }
}
